package com.bocai.kelalacar.ui.car.order.act;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bocai.kelalacar.App;
import com.bocai.kelalacar.R;
import com.bocai.kelalacar.base.BaseActivity;
import com.bocai.kelalacar.bean.CarDriverBean;
import com.bocai.kelalacar.bean.MyGradOrderBean;
import com.bocai.kelalacar.bean.MyPublishStrokeBean;
import com.bocai.kelalacar.bean.OrderDetailBean;
import com.bocai.kelalacar.ui.car.main.act.MainActivity;
import com.bocai.kelalacar.ui.car.order.contract.MyOrderContract;
import com.bocai.kelalacar.ui.car.order.module.MyOrderModule;
import com.bocai.kelalacar.ui.car.order.presenter.MyOrderPresenter;
import com.bocai.kelalacar.ui.car.set.act.AddCarActivity;
import com.bocai.kelalacar.ui.car.set.act.AddDriverActivity;
import com.bocai.kelalacar.ui.car.set.act.CarManageActivity;
import com.bocai.kelalacar.ui.car.set.act.DriverMangerActivity;
import com.bocai.kelalacar.util.DateUtil;
import com.bocai.kelalacar.util.SP;
import com.bocai.kelalacar.widget.SpinnerDialog;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yuanfei on 2017/6/21.
 */

public class RushOrderDetailActivity extends BaseActivity implements MyOrderContract.view {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.tv_car_information)
    TextView tvCarInformation;
    @BindView(R.id.tv_start_address)
    TextView tvStartAddress;
    @BindView(R.id.tv_end_address)
    TextView tvEndAddress;
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;
    @BindView(R.id.tv_order_name)
    TextView tvOrderName;
    @BindView(R.id.tv_travel_data)
    TextView tvTravelData;
    @BindView(R.id.tv_travel_phone)
    TextView tvTravelPhone;
    @BindView(R.id.ll_you_information)
    LinearLayout llYouInformation;
    @BindView(R.id.ll_travel)
    LinearLayout llTravel;
    @BindView(R.id.tv_select_car)
    TextView tvSelectCar;
    @BindView(R.id.ll_select_car)
    LinearLayout llSelectCar;
    @BindView(R.id.tv_select_driver)
    TextView tvSelectDriver;
    @BindView(R.id.ll_select_driver)
    LinearLayout llSelectDriver;
    @Inject
    MyOrderPresenter presenter;
    String orderId;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.tv_car_info)
    TextView tvCarInfo;
    @BindView(R.id.tv_car_num1)
    TextView tvCarNum1;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ll_select)
    LinearLayout llSelect;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.ll_car_information)
    LinearLayout llCarInformation;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_end_data)
    TextView tvEndData;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    List<CarDriverBean.ContentBean.CarListBean> carListBeen = new ArrayList<>();
    List<CarDriverBean.ContentBean.DriverListBean> driverListBeen = new ArrayList<>();
    String carId;
    String driverId;
    int index = 0;
    OrderDetailBean bean;
    @BindView(R.id.ll_back)
    LinearLayout llBack;

    @Override
    public int getLayoutId() {
        return R.layout.act_rush_order_detail;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new MyOrderModule(this)).inject(this);
    }

    @Override
    public void initView() {
        initToolbar("我的行程");
        initBack(imgBack,llBack);
        orderId = getIntent().getStringExtra("orderId");
        presenter.orderDetail(orderId);
        if ((int)SP.get(this,"MemberType",0) == 2) {
            presenter.getCarDriverList(SP.get(this, "id", "").toString());
        }
    }
    @OnClick({R.id.ll_select_car,R.id.ll_select_driver,R.id.btn,R.id.right_btn})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.ll_select_car:
                new SpinnerDialog(this).builder().setCarList(carListBeen, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (position == 0){

                        }else if (position == carListBeen.size() + 1){
                            startActivityForResult(new Intent(RushOrderDetailActivity.this, CarManageActivity.class),234);
//                            startActivity(AddCarActivity.class);
                        }else {
                            position = position - 1;
                            carId = carListBeen.get(position).getCarId();
                            tvSelectCar.setText(carListBeen.get(position).getCarLicense() + "   " + carListBeen.get(position).getSeats() + "座");
                        }
                    }
                }).show();
                break;
            case R.id.ll_select_driver:
                new SpinnerDialog(this).builder().setDriverList(driverListBeen, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (position == 0){

                        }else if (position == driverListBeen.size() + 1){
                            startActivityForResult(new Intent(RushOrderDetailActivity.this, DriverMangerActivity.class),234);
//                            startActivity(AddDriverActivity.class);
                        }else {
                            position = position - 1;
                            driverId = driverListBeen.get(position).getDriverId();
                            tvSelectDriver.setText(driverListBeen.get(position).getDriverName());
                        }
                    }
                }).show();
                break;
            case R.id.btn:
                if (index == 2){
                    if (TextUtils.isEmpty(carId)){
                        showErrorTip("请选择出发车辆");
                    }else if (TextUtils.isEmpty(driverId)){
                        showErrorTip("请选择出发司机");
                    }else {
                        presenter.teamArrange(orderId,carId,driverId);
                    }
                }else if (index == 3){
                    if (TextUtils.isEmpty(bean.getStartTime())) {
                        presenter.startStroke(orderId);
                    }else {
                        presenter.finishOrder(orderId);
                    }
                }
                break;
            case R.id.right_btn:
                Intent intent = new Intent(RushOrderDetailActivity.this,ChangeCarAndDriverActivity.class);
                intent.putExtra("orderId",orderId);
                startActivityForResult(intent,345);
                break;
        }
    }

    @Override
    public void myStrokePublish(MyPublishStrokeBean bean) {

    }

    @Override
    public void myGradOrder(MyGradOrderBean bean) {

    }

    /**
     * 订单状态【0-待接单】【1-待付款】【2-待出发】【3-已完成】【4-已关闭】 【5-行程中】
     *
     * @param bean
     */
    @Override
    public void getOrderDetail(OrderDetailBean bean) {
        this.bean = bean;
        ll2.setVisibility(View.GONE);
        tvStartAddress.setText(bean.getOriginCity());
        tvEndAddress.setText(bean.getArriveCity());
        tvCarNum.setText(bean.getApplySeats()+"座");
        tvTravelData.setText(bean.getAppointTime());

        if (bean.getOrderStatus() == 1) {
            String bb = bean.getMemberPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1********");
            tvTravelPhone.setText(bb);
            tvOrderName.setText(bean.getMemberName().substring(0,1)+"**");
            index = 1;
            ll1.setVisibility(View.VISIBLE);
            llTravel.setVisibility(View.VISIBLE);
            llCarInformation.setVisibility(View.GONE);
            llSelect.setVisibility(View.GONE);
            btn.setVisibility(View.GONE);
            tvContent.setText("抢单成功！请等待旅行社付款");
        } else if (bean.getOrderStatus() == 2 && TextUtils.isEmpty(bean.getDriver())) {
            String bb = bean.getMemberPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1********");
            tvTravelPhone.setText(bean.getMemberPhone());
            tvOrderName.setText(bean.getMemberName());
            index = 2;
            ll1.setVisibility(View.GONE);
            llTravel.setVisibility(View.VISIBLE);
            llCarInformation.setVisibility(View.GONE);
            llSelect.setVisibility(View.VISIBLE);
            btn.setVisibility(View.VISIBLE);
            btn.setText("提交");
            countDown(bean.getOrderTime());
        } else if ((bean.getOrderStatus() == 2||bean.getOrderStatus() == 5) && !TextUtils.isEmpty(bean.getDriver())) {
            tvTravelPhone.setText(bean.getMemberPhone());
            tvOrderName.setText(bean.getMemberName());
            index = 3;

            rightBtn.setVisibility(View.VISIBLE);
            rightBtn.setText("变更车辆司机");

            if ((int)SP.get(this,"MemberType",0) == 3){
                rightBtn.setVisibility(View.GONE);
            }
            ll1.setVisibility(View.VISIBLE);
            llTravel.setVisibility(View.VISIBLE);
            llCarInformation.setVisibility(View.VISIBLE);
            llSelect.setVisibility(View.GONE);
            btn.setVisibility(View.VISIBLE);
            tvContent.setText("旅行社已付款，行程结束后会将佣金发放至您的账号");
            btn.setText("开始行程");
            tvCarInfo.setText(bean.getCarSeats()+"座客车 "+bean.getCarLicense());
            tvCarNum1.setText(bean.getCarSeats()+"座");
            tvName.setText(bean.getDriver());
            tvPhone.setText(bean.getDriverPhone());
            if (!TextUtils.isEmpty(bean.getStartTime())){
                rightBtn.setVisibility(View.GONE);
//                rightBtn.setVisibility(View.VISIBLE);
                btn.setEnabled(false);
                countDown1(bean.getStartTime());
            }
        } else if (bean.getOrderStatus() == 3) {
            tvTravelPhone.setText(bean.getMemberPhone());
            tvOrderName.setText(bean.getMemberName());
            index = 4;
            ll2.setVisibility(View.VISIBLE);
            ll1.setVisibility(View.GONE);
            llTravel.setVisibility(View.VISIBLE);
            llCarInformation.setVisibility(View.VISIBLE);
            llSelect.setVisibility(View.GONE);
            btn.setVisibility(View.GONE);
            tvCarInfo.setText(bean.getCarSeats()+"座客车 "+bean.getCarLicense());
            tvCarNum1.setText(bean.getCarSeats()+"座");
            tvName.setText(bean.getDriver());
            tvPhone.setText(bean.getDriverPhone());
            tvEndData.setText("订单已于"+bean.getFinishTime()+" 结束");
        }
    }

    /**
     * 倒计时
     */
    public void countDown(String time) {

            Date startDate = DateUtil.setStringToData(time);
            Date date = new Date();
            long between = 2*60*60*1000 - (date.getTime() - startDate.getTime());

                CountDownTimer countDownTimer = new CountDownTimer(between, 1) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        tvTime.setText("请在 "+DateUtil.formatTime3(millisUntilFinished)+" 内完善您的车辆信息");
                    }

                    @Override
                    public void onFinish() {
//                        showErrorTip("订单关闭");
//                        finish();
                        String bb = bean.getMemberPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1********");
                        tvTravelPhone.setText(bb);
                        tvOrderName.setText(bean.getMemberName().substring(0,1)+"**");
                        index = 1;
                        ll2.setVisibility(View.VISIBLE);
                        ll1.setVisibility(View.GONE);
                        llTravel.setVisibility(View.VISIBLE);
                        llCarInformation.setVisibility(View.GONE);
                        llSelect.setVisibility(View.GONE);
                        btn.setVisibility(View.GONE);
                        tvEndData.setText("订单已关闭");

                    }
                };
                countDownTimer.start();
    }

    public void countDown1(final String time) {
        Date startDate = DateUtil.setStringToData(time);
        Date date = new Date();
        long between = 3*60*60*1000 - (date.getTime() - startDate.getTime());

        if (between>=0) {

            CountDownTimer countDownTimer = new CountDownTimer(between, 1) {
                @Override
                public void onTick(long millisUntilFinished) {
                    btn.setText(DateUtil.formatTime3(millisUntilFinished) + " 后可以结束行程");
//                if (millisUntilFinished == 1){
//                    btn.setEnabled(true);
//                    btn.setText("完成行程");
//                }
                }

                @Override
                public void onFinish() {
                    btn.setEnabled(true);
                    btn.setText("完成行程");
                }
            };
            countDownTimer.start();
        }else {
            btn.setEnabled(true);
            btn.setText("完成行程");
        }
    }

    @Override
    public void getCarDriverList(CarDriverBean bean) {
        carListBeen = bean.getContent().getCarList();
        driverListBeen = bean.getContent().getDriverList();
    }

    @Override
    public void teamArrangeSuccess() {
        showErrorTip("提交成功");
        presenter.orderDetail(orderId);
    }

    @Override
    public void startStrokeSuccess() {
        showErrorTip("行程开始");
        presenter.orderDetail(orderId);
    }

    @Override
    public void cancelOrderSuccess() {

    }

    @Override
    public void finishOrderSuccess() {
        showErrorTip("完成订单");
        presenter.orderDetail(orderId);
    }

    @Override
    public void showLoading(String title) {
        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {
        showShortToast(msg);
        if (msg.equals("您的登录已失效，请重新登录")){
            startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 234){
            if ((int)SP.get(this,"MemberType",0) == 2) {
                presenter.getCarDriverList(SP.get(this, "id", "").toString());
            }
        }else if (requestCode == 345&&resultCode == 345){
            presenter.orderDetail(orderId);
        }
    }
}
